package com.example.gulimallproduct.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.common.utils.R;
import com.example.gulimallproduct.dao.AttrDao;
import com.example.gulimallproduct.entity.AttrAttrgroupRelationEntity;
import com.example.gulimallproduct.entity.AttrEntity;
import com.example.gulimallproduct.entity.CategoryEntity;
import com.example.gulimallproduct.eumn.AttrType;
import com.example.gulimallproduct.request.AttrAttrGroupRelationRequest;
import com.example.gulimallproduct.response.SelectAttrGroupWithAttrsResponse;
import com.example.gulimallproduct.service.AttrAttrgroupRelationService;
import com.example.gulimallproduct.service.AttrService;
import com.example.gulimallproduct.service.CategoryService;
import com.example.gulimallproduct.utlis.SetCatelogPathUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.gulimallproduct.dao.AttrGroupDao;
import com.example.gulimallproduct.entity.AttrGroupEntity;
import com.example.gulimallproduct.service.AttrGroupService;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Autowired
    private AttrDao attrDao;
    @Autowired
    private AttrService attrService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<>()
        );
        return new PageUtils(page);
    }

    @Override
    public R selectPage(Map<String, Object> params, Long catId) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new LambdaQueryWrapper<AttrGroupEntity>()
                        .eq(catId != 0,AttrGroupEntity::getCatelogId, catId)
                        .and(StringUtils.isNotBlank(params.get("key").toString()),
                                qw->qw.likeRight(AttrGroupEntity::getAttrGroupName, params.get("key"))
                                        .or().eq(AttrGroupEntity::getAttrGroupId, params.get("key"))
                        )
        );
        return R.ok().put("page", new PageUtils(page));
    }

    @Override
    public R getInfoById(Long attrGroupId) {
        AttrGroupEntity attrGroup = this.getById(attrGroupId);
        CategoryEntity categoryEntity = categoryService.getById(attrGroup.getCatelogId());
        LinkedList<Long> catelogPath = SetCatelogPathUtils.getCatelogPath(categoryEntity, categoryService);
        attrGroup.setCatelogPath(catelogPath);
        return R.ok().put("attrGroup", attrGroup);
    }

    /**
     * 查询分组下没有关联的属性
     */
    @Override
    public R attrNoRelation(Map<String, Object> params, Long attrGroupId) {
        // 查询分组下关联的属性
        List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationService.lambdaQuery().eq(AttrAttrgroupRelationEntity::getAttrGroupId, attrGroupId).list();
        List<Long> attrIds = entities.stream().map(AttrAttrgroupRelationEntity::getAttrId).toList();
        if(CollectionUtil.isNotEmpty(attrIds)){
            // 查询所有属性，排除关联的属性
            IPage<AttrEntity> page = attrService.page(new Query<AttrEntity>().getPage(params),
                    new LambdaQueryWrapper<AttrEntity>()
                            .notIn(AttrEntity::getAttrId, attrIds)
                            .eq(AttrEntity::getAttrType, AttrType.BASE.getCode()));
            return R.ok().put("page", new PageUtils(page));
        }
        return R.ok().put("page", new PageUtils(new Page<>(1, 10)));
    }

    /**
     * 查询分组下关联的属性
     */
    @Override
    public R attrRelation(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> entities = attrAttrgroupRelationService.lambdaQuery().eq(AttrAttrgroupRelationEntity::getAttrGroupId, attrGroupId).list();
        List<Long> attrIds = entities.stream().map(AttrAttrgroupRelationEntity::getAttrId).toList();
        List<AttrEntity> attrEntities = attrService.listByIds(attrIds);

        return R.ok().put("data", attrEntities);
    }

    @Override
    public R SaveRelation(List<AttrAttrGroupRelationRequest> list) {

        // 验证属性分组和属性是否存在
        List<Long> attrGroupIdList = list.stream().map(AttrAttrGroupRelationRequest::getAttrGroupId).toList();
        Long attrGroupCount = lambdaQuery().in(AttrGroupEntity::getAttrGroupId, attrGroupIdList).count();
        if(attrGroupCount!=list.size()){
            return R.error("属性分组不存在");
        }
        // 验证属性是否存在
        List<Long> attrIdList = list.stream().map(AttrAttrGroupRelationRequest::getAttrId).toList();
        Long attrCount = attrService.lambdaQuery().in(AttrEntity::getAttrId, attrIdList).count();
        if(attrCount!=list.size()){
            return R.error("属性不存在");
        }
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = new LinkedList<>();
        for (AttrAttrGroupRelationRequest attrAttrGroupRelationRequest : list) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(attrAttrGroupRelationRequest, attrAttrgroupRelationEntity);
            attrAttrgroupRelationEntities.add(attrAttrgroupRelationEntity);
        }
        // 保存关联关系
        attrAttrgroupRelationService.saveBatch(attrAttrgroupRelationEntities);
        return R.ok();
    }

    @Override
    public R delRelation(List<AttrAttrGroupRelationRequest> list) {
        LambdaQueryWrapper<AttrAttrgroupRelationEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(CollectionUtil.isNotEmpty( list)){
            //拼接删除条件
            for (AttrAttrGroupRelationRequest relation : list) {
                lambdaQueryWrapper.or(
                        qw->qw.eq(AttrAttrgroupRelationEntity::getAttrGroupId, relation.getAttrGroupId())
                                .eq(AttrAttrgroupRelationEntity::getAttrId, relation.getAttrId())
                );
            }
        }
        // 删除关联关系
        attrAttrgroupRelationService.remove(lambdaQueryWrapper);
        return R.ok();
    }

    @Override
    public R getAttrGroupWithAttrs(Long catelogId) {
        List<AttrGroupEntity> attrGroupEntities = lambdaQuery().eq(AttrGroupEntity::getCatelogId, catelogId).list();
        if(CollectionUtil.isEmpty(attrGroupEntities)){
            return R.error("属性分组不存在");
        }
        List<SelectAttrGroupWithAttrsResponse> responses = new LinkedList<>();
        for (AttrGroupEntity attrGroupEntity : attrGroupEntities) {
            SelectAttrGroupWithAttrsResponse response = new SelectAttrGroupWithAttrsResponse();
            BeanUtils.copyProperties(attrGroupEntity, response);
            List<AttrEntity> Attrs= attrDao.selectAttrGroupWithAttrs(response.getAttrGroupId());
            response.setAttrs(Attrs);
            responses.add(response);
        }
        return R.ok().put("data", responses);
    }

}